package cn.tedu.vue_master.interceptor;

import cn.tedu.vue_master.exception.ACServiceException;
import cn.tedu.vue_master.restful.ServiceCode;
import io.netty.handler.codec.base64.Base64Encoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Slf4j
@Component
public class BasicAuthInterceptor implements HandlerInterceptor {

    @Value("${vue_master.username}")
    private String username;
    @Value("${vue_master.password}")
    private String password;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String auth = request.getHeader("Authorization");
        log.debug("auth = {}",auth);
        if (StringUtils.hasText(auth)) {
            log.debug("BasicAuthInterceptor的preHandle获取auth = {}", auth);
            // 获取项目中保存的用户名和密码，以用于比对
            String checkAuth = username + ":" + password;
            byte[] bytes = checkAuth.getBytes(StandardCharsets.UTF_8);
            //byte[] bytes = ("root:root").getBytes(StandardCharsets.UTF_8);
            // 采用Base64编码
            String encode = "Basic " + Base64.getEncoder().encodeToString(bytes);
            log.debug("项目中用户名和密码编码后，encode = {}", encode);
            // 与传入的Authorization进行对比
            if (auth.equals(encode)) {
                return true;
            }
            log.error("auth 认证失败！");
        }
        else {
            //抛出异常处理
            throw new ACServiceException(ServiceCode.ERR_BAD_REQUEST, "auth 认证信息不存在！！！");
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
